import React, { useRef, useState, useEffect, Fragment } from "react";
import { AppstoreOutlined, DownOutlined } from "@ant-design/icons";
import { Dropdown, Drawer, Image, Tour, Space, Divider, theme } from "antd";
import { useTranslation } from "react-i18next";
import { titleCheck, logoImg, post_axios, text_check } from "../../utils";
import ChangePwd from "../login/changePwd";
import cookie from "react-cookies";

export default function Topnav(props) {
  const { t } = useTranslation();

  const { user_msg, menu_select, menu_data } = props;

  const menuClickFunc = (item) => {
    setDrawerOpen(false);
    menu_select(item);
  };

  const tourRef = useRef(null);
  const [tourOpen, setTourOpen] = useState(false);
  const steps = [
    {
      title: t("common.info"),
      description: t("index.click_show_menu"),
      target: () => tourRef.current,
      placement: "bottomRight",
    },
  ];

  const TourOnFinish = () => {
    localStorage.setItem("user_logined", "1");
  };

  const [drawerOpen, setDrawerOpen] = useState(false);
  const drawer_menu_show_func = () => {
    if (drawerOpen) return;
    setDrawerOpen(true);
  };

  const back_to_mg = async () => {
    const company = sessionStorage.getItem("company");
    if (company !== "mg") return;

    let upMsg = {};
    let res = await post_axios("mega_jump", "go", upMsg);
    if (!res) return;
    console.log(res.data.param);
    let data = res.data.param;
    let qStr = Object.keys(data)
      .map((v) => `${v}=${encodeURI(data[v])}`)
      .join("&");
    window.location.href = `${res.data.url}?${qStr}`;
  };

  const { useToken } = theme;
  const { token } = useToken();
  const contentStyle = {
    backgroundColor: token.colorBgElevated,
    borderRadius: token.borderRadiusLG,
    boxShadow: token.boxShadowSecondary,
  };
  const menuStyle = {
    boxShadow: "none",
  };

  const { name, username } = user_msg;
  const items = [
    {
      key: "1",
      method: "change_password",
      label: (
        <p>
          {text_check({
            msg_cn: "修改密码",
            msg_en: "Change Password",
          })}
        </p>
      ),
    },
    {
      key: "2",
      method: "quit",
      label: (
        <p>
          {text_check({
            msg_cn: "退出",
            msg_en: "Logout",
          })}
        </p>
      ),
    },
  ];

  const dropTitle = text_check({
    msg_cn: "欢迎," + name + " " + username,
    msg_en: "Welcome," + name + " " + username,
  });

  const [changePwdShow, setChangePwdShow] = useState(false);

  const userMenuFunc = async (item) => {
    if (item.key === "1") {
      setChangePwdShow(true);
      return;
    } else if (item.key === "2") {
      let res = await post_axios("login_out", "out", {});
      if (!res) return;
      cookie.remove("login_timer");
      window.location.reload();
      return;
    }
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    if (localStorage.getItem("user_logined") !== "1") {
      setTourOpen(true);
    }
  }, []);

  return (
    <>
      <div className="Topnav">
        <div className="nav_left_box">
          <div className="menu_btn" onClick={drawer_menu_show_func}>
            <AppstoreOutlined ref={tourRef} style={{ fontSize: "26px" }} />
          </div>
          <Tour
            open={tourOpen}
            onClose={() => setTourOpen(false)}
            steps={steps}
            onFinish={TourOnFinish}
          />

          <div className="logo" onClick={back_to_mg}>
            <Image
              height="40px"
              src={logoImg()}
              fit="contain"
              preview={false}
            />
          </div>
        </div>
        <div className="top_nav_title">{titleCheck()}</div>
        <div className="user_btn">
          <Dropdown
            menu={{
              items,
            }}
            dropdownRender={(menu) => (
              <div style={contentStyle}>
                {React.cloneElement(menu, {
                  style: menuStyle,
                  onClick: userMenuFunc,
                })}
                <Divider
                  style={{
                    margin: 0,
                  }}
                />
                <Space
                  style={{
                    padding: 8,
                  }}
                ></Space>
              </div>
            )}
          >
            <div onClick={(e) => e.preventDefault()}>
              <Space>
                {dropTitle}
                <DownOutlined />
              </Space>
            </div>
          </Dropdown>
        </div>
      </div>

      <ChangePwd
        changePwdShow={changePwdShow}
        setChangePwdShow={setChangePwdShow}
        username={user_msg.username}
      />

      <Drawer
        title={titleCheck()}
        onClose={() => setDrawerOpen(false)}
        open={drawerOpen}
        placement="left"
        closeIcon={false}
        forceRender={true}
        size="large"
      >
        <div className="drawer_menu_content">
          {menu_data.map((level1) => {
            return (
              <div className="menu_box" key={level1.id}>
                <div className="menu_level_1" key={level1.id}>
                  {text_check(level1)}
                </div>
                {level1.children.map((level2) => {
                  return level2.children ? (
                    <Fragment key={level2.id}>
                      <div className="menu_level_2">{text_check(level2)}</div>
                      {level2.children.map((level3) => {
                        return (
                          <div
                            className="menu_level_3 can_click"
                            onClick={() => menuClickFunc(level3)}
                            key={level3.id}
                          >
                            {text_check(level3)}
                          </div>
                        );
                      })}
                    </Fragment>
                  ) : (
                    <div
                      className="menu_level_2 can_click"
                      onClick={() => menuClickFunc(level2)}
                      key={level2.id}
                    >
                      {text_check(level2)}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
      </Drawer>
    </>
  );
}
